﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Linq;
using System.Data.Linq;
using Hxsoft.AppV1;
using Hxsoft.AppV1.Module;

namespace Hxsoft.AppV1.Admin.RoleManage.Controls
{
	public partial class Accredit : BaseUserControl
	{
		/// <summary>
		/// 资源类别标识。
		/// </summary>
		public Guid CategoryId
		{
			get
			{
				object o = ViewState["CategoryId"];
				return o == null ? default(Guid) : (Guid)o;
			}
			set { ViewState["CategoryId"] = value; }
		}

		/// <summary>
		/// 资源代码。
		/// </summary>
		public string ResourceCode
		{
			get { return (string)ViewState["ResourceCode"]; }
			set { ViewState["ResourceCode"] = value; }
		}
		/// <summary>
		/// 用户标识。
		/// </summary>
		public Guid? UserId
		{
			get { return (Guid?)ViewState["UserId"]; }
			set { ViewState["UserId"] = value; }
		}

		/// <summary>
		/// 权限状态集合。
		/// </summary>
		public List<PermissionState> PermissionsStatus
		{
			get
			{
				EnsureAccreditTree();
				List<PermissionState> permissionsState = new List<PermissionState>();

				foreach (RepeaterItem item in RptResourceList.Items)
				{
					Guid resourceId = GetListItemIdentifier(item);

					// 创建权限复选框
					Label permissionBox = (Label)item.FindControl("LblPermission");
					List<Permission> permissions = Permissions.GetItemsByResourceId(resourceId);

					foreach (Permission permission in permissions)
					{
						CheckBox permissionCheckBox = (CheckBox)permissionBox.FindControl(permission.PermissionCode.ToString());
						if (permissionCheckBox != null)
						{
							PermissionState permissionStatus = new PermissionState();

							permissionStatus.ResourceId = permission.ResourceId;
							permissionStatus.PermissionCode = permission.PermissionCode;
							permissionStatus.IsEnabled = permissionCheckBox.Checked;

							permissionsState.Add(permissionStatus);
						}
					}
				}

				return permissionsState;
			}
			set
			{
				EnsureAccreditTree();
				foreach (RepeaterItem item in RptResourceList.Items)
				{
					Guid resourceId = GetListItemIdentifier(item);

					// 创建权限复选框
					Label permissionBox = (Label)item.FindControl("LblPermission");
					List<Permission> permissions = Permissions.GetItemsByResourceId(resourceId);

					foreach (Permission permission in permissions)
					{
						CheckBox permissionCheckBox = (CheckBox)permissionBox.FindControl(permission.PermissionCode.ToString());
						if (permissionCheckBox != null)
						{
							foreach (PermissionState permissionState in value)
							{
								if (permission.ResourceId == permissionState.ResourceId && permission.PermissionCode == permissionState.PermissionCode)
									permissionCheckBox.Checked = permissionState.IsEnabled;
							}
						}
					}
				}
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			EnsureLoadResourcePermissionCheckBox();
		}

		protected string GroupStartTag = "";
		protected string GroupEndTag = "";
		protected string GroupCollapseImgTag = "";
		private Stack<Guid> ParentResourceIdStack = new Stack<Guid>();
		protected Guid? PreResourceId;
		protected void RptResourceList_ItemCreated(object sender, RepeaterItemEventArgs e)
		{
			if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
			{
				// 实现展开树
				GroupStartTag = "";

				Resource node = (Resource)e.Item.DataItem;
				if (node == null)
					return;

				if (node.ParentResourceId != null && node.ParentResourceId == PreResourceId)
				{
					GroupStartTag += "<div id=\"" + RptResourceList.ClientID + "_ResourceGroup" + PreResourceId + "\">";
					ParentResourceIdStack.Push(PreResourceId.Value);
				}
				else
				{
					if (node.ParentResourceId.HasValue)
					{
						while (ParentResourceIdStack.Count > 0 && ParentResourceIdStack.Peek() != node.ParentResourceId.Value)
						{
							GroupStartTag = "</div>" + GroupStartTag;
							ParentResourceIdStack.Pop();
						}
					}
					else
					{
						while (ParentResourceIdStack.Count > 0)
						{
							GroupStartTag = "</div>" + GroupStartTag;
							ParentResourceIdStack.Pop();
						}
					}
				}

				if (PreResourceId != null)
					GroupStartTag = "</div>" + GroupStartTag;

				if (node.ParentResourceId != null)
					GroupStartTag += "<div id=\"" + RptResourceList.ClientID + "_ResourceItem" + node.ResourceId + "\" pid=\"" + node.ParentResourceId.Value + "\">";
				else
					GroupStartTag += "<div id=\"" + RptResourceList.ClientID + "_ResourceItem" + node.ResourceId + "\">";

				PreResourceId = node.ResourceId;

				GroupCollapseImgTag = "<img id=\"" + RptResourceList.ClientID + "_GroupCollapseImg" + PreResourceId.Value + "\" style=\"margin-left:" + (ParentResourceIdStack.Count * 20) + "px; cursor:pointer;\" src=\"../I/fk_minus.gif\" width=\"15\" height=\"15\" border=\"0\" onclick=\"" + this.ClientID + "_SetResourceGroupExpanded('" + PreResourceId.Value + "');\">";
			}

			if (e.Item.ItemType == ListItemType.Footer)
			{
				GroupEndTag = "";

				if (PreResourceId != null)
					GroupEndTag += "</div>";

				while (ParentResourceIdStack.Count > 0)
				{
					GroupEndTag += "</div>";
					ParentResourceIdStack.Pop();
				}

				PreResourceId = null;
			}
		}

		/// <summary>
		/// 取得 ListItem 的标识符。
		/// </summary>
		/// <param name="item">列表的 ListItem。</param>
		/// <returns>ListItem 的标识符。</returns>
		protected Guid GetListItemIdentifier(RepeaterItem item)
		{
			Guid identifier;
			HiddenField control;

			control = (HiddenField)item.FindControl("Identifier_ResourceId");
			identifier = new Guid(control.Value);

			return identifier;
		}


		/// <summary>
		/// 是否绑定的资源列表。
		/// </summary>
		protected bool IsBindResourceList
		{
			get
			{
				object o = ViewState["IsBindResourceList"];
				return o == null ? false : (bool)o;
			}
			set { ViewState["IsBindResourceList"] = value; }
		}

		/// <summary>
		/// 重置
		/// </summary>
		public void Reset()
		{
			RptResourceList.Controls.Clear();
			IsBindResourceList = false;
			_isLoadResourcePermissionCheckBox = false;
		}

		/// <summary>
		/// 确保授权树的构建。
		/// </summary>
		protected void EnsureAccreditTree()
		{
			if (!IsBindResourceList)
				this.DataBind();
			else
				EnsureLoadResourcePermissionCheckBox();
		}

		/// <summary>
		/// 确保绑定了资源列表。
		/// </summary>
		protected void EnsureBindResourceList()
		{
			if (!IsBindResourceList)
			{
				BindResourceList();
				IsBindResourceList = true;
				_isLoadResourcePermissionCheckBox = false;
			}
		}

		/// <summary>
		/// 确保加载了资源权限复选框。
		/// </summary>
		protected void EnsureLoadResourcePermissionCheckBox()
		{
			if (!_isLoadResourcePermissionCheckBox)
			{
				LoadResourcePermissionCheckBox();
				_isLoadResourcePermissionCheckBox = true;
			}
		}

		/// <summary>
		/// 绑定资源列表。
		/// </summary>
		protected void BindResourceList()
		{
			List<Resource> resources = new List<Resource>();

			List<Resource> roots = new List<Resource>();
			if (!string.IsNullOrEmpty(ResourceCode))	// 仅显示指定资源的列表
			{
				Resource resource = Resources.GetItem(CategoryId, SiteId, ResourceCode, true);
				if (resource != null)
					roots.Add(resource);
			}
			else
			{
				if (SiteId.HasValue)
				{
					roots = Resources.GetRoots(CategoryId, null, true);
					roots.AddRange(Resources.GetRoots(CategoryId, SiteId, true));
				}
				else
					roots = Resources.GetRoots(CategoryId, true);
			}

			foreach (Resource root in roots)
			{
				resources.Add(root);
				AppendChildNodes(resources, root);
			}

			RptResourceList.DataSource = resources;
		}

		private bool _isLoadResourcePermissionCheckBox = false;
		/// <summary>
		/// 加载资源权限框。
		/// </summary>
		protected void LoadResourcePermissionCheckBox()
		{
			foreach (RepeaterItem item in RptResourceList.Items)
			{
				Guid resourceId = GetListItemIdentifier(item);

				// 创建权限复选框
				Label permissionBox = (Label)item.FindControl("LblPermission");
				List<Permission> permissions = Permissions.GetItemsByResourceId(resourceId);
				AccessController ac = new AccessController();
				string userName = null;
				if(UserId.HasValue)
					userName = Users.GetUserName(UserId.Value);

				foreach (Permission permission in permissions)
				{
					CheckBox permissionCheckBox = new CheckBox();
					permissionCheckBox.ID = permission.PermissionCode.ToString();
					permissionCheckBox.InputAttributes["value"] = permission.PermissionCode.ToString();
					permissionCheckBox.InputAttributes["onclick"] = this.ClientID + "_CheckItem(this, '" + permission.ResourceId + "');";
					permissionCheckBox.Text = permission.PermissionName;

					if (!ac.GetUserIsHasPermission<object>(userName, null, permission.ResourceId, permission.PermissionCode, SiteId))
						permissionCheckBox.Enabled = false;

					permissionBox.Controls.Add(permissionCheckBox);
				}
			}
		}

		/// <summary>
		/// 附加子节点到资源集合中。
		/// </summary>
		/// <param name="resources">资源集合。</param>
		/// <param name="parent">父节点。</param>
		protected void AppendChildNodes(List<Resource> resources, Resource parent)
		{
			List<Resource> nodes;
			if (SiteId.HasValue)
			{
				nodes = parent.Children.Where(p => p.SiteId == null).ToList();
				nodes.AddRange(parent.Children.Where(p => p.SiteId == SiteId.Value).ToList());
			}
			else
				nodes = parent.Children.ToList();

			foreach (Resource node in nodes)
			{
				resources.Add(node);
				AppendChildNodes(resources, node);
			}
		}

		protected void RptResourceList_DataBinding(object sender, EventArgs e)
		{
			EnsureBindResourceList();
		}

		public override void DataBind()
		{
			base.DataBind();
			EnsureLoadResourcePermissionCheckBox();
		}
	}
}